<?php
/**
 * Created by PhpStorm.
 * User: j
 * Date: 2018-12-18
 * Time: 16:32
 */
namespace common\services\qiniu;

use Yii;
use Qiniu\Auth;
use api\components\ApiException;
use common\services\config\Config;
use common\services\tool\ToolHttp;

class QiNiuService
{
    public function __construct()
    {
        $this->config       = Yii::$app->params['qiniu'];
        $this->accessKey    = $this->config['accessKey'];
        $this->secretKey    = $this->config['secretKey'];
        $this->storageSpace = $this->config['storageSpace']['hxGame'];
        $this->cdn          = $this->config['cdn'];
        $this->upHost       = $this->config['upHost'];
        $this->rsHost       = $this->config['rsHost'];
        $this->rsfHost      = $this->config['rsfHost'];
    }

    /**
     * 个人中心头像上传（七牛）
     * @param $filePath
     * @return string
     * @throws ApiException
     */
    public function pictureFileUpload($filePath)
    {
        if (empty($filePath)) {
            throw new ApiException(Config::$qiniuFileNull['message'], Config::$qiniuFileNull['code']);
        }

        $result = $this->QiNiuUpload($filePath);
        if (empty($result) || !is_array($result)) {
            throw new ApiException(Config::$qiniuError['message'], Config::$qiniuError['code']);
        }

        return $this->cdn . $result['key'];
    }

    // ----------------------------------- 基础方法 -----------------------------------

    /**
     * 七牛上传，文件上传基础接口
     * @param $filePath
     * @param null $key
     * @param string $storageSpace
     * @return false|string
     * @throws ApiException
     */
    public function QiNiuUpload($filePath, $key = null, $storageSpace = '')
    {
        if (!file_exists($filePath)) {
            throw new ApiException(Config::$qiniuFileNull['message'], Config::$qiniuFileNull['code']);
        }

        $data = [];

        // 获取存储空间
        $storageSpace = $storageSpace ? $storageSpace : $this->storageSpace;

        // 初始化存储空间对象
        $auth = new Auth($this->accessKey, $this->secretKey);
        $uploadToken = $auth->uploadToken($storageSpace);

        if (class_exists('\CURLFile')) {
            $data['file'] = new \CURLFile($filePath);
        } else {
            $data['file'] = '@' . $filePath;
        }
        if ($key) {
            $data['key'] = $key;
        }
        $data['token'] = $uploadToken;

        // 请求
        $result = ToolHttp::QiNiuHttpCurl($data, $this->upHost);
        if (!$result) {
            throw new ApiException(Config::$qiniuError['message'], Config::$qiniuError['code']);
        }
        return $result;
    }
}
